package com.naiterui.ehp.bs.cms.modules.devops.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.utils.FileUtil;
import com.naiterui.ehp.bs.cms.common.exception.BusinessExceptionCode;
import com.naiterui.ehp.bs.cms.modules.devops.entity.SysInitFileConfig;
import com.naiterui.ehp.bs.cms.modules.devops.mapper.SysInitFileConfigMapper;
import com.naiterui.ehp.bs.cms.modules.devops.service.ISysInitFileConfigService;
import com.naiterui.ehp.bs.cms.modules.devops.vo.SysInitFileConfigVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统初始化文件配置
 *
 * @author yangfuya
 * @since 2022/4/25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysInitFileConfigServiceImpl implements ISysInitFileConfigService {

    private final SysInitFileConfigMapper sysInitFileConfigMapper;
    @Value("${file.base.prefix}")
    private String fileBasePrefix;

    @Override
    public List<SysInitFileConfigVO> list() {
        List<SysInitFileConfig> list = this.sysInitFileConfigMapper
                .selectList(Wrappers.lambdaQuery(SysInitFileConfig.class).orderByAsc(SysInitFileConfig::getType));
        return list.stream()
                .map(l -> SysInitFileConfigVO.builder().id(l.getId()).name(l.getName()).type(l.getType()).path(l.getPath())
                        .remarks(l.getRemarks()).checked(l.getChecked()).createdAt(l.getCreatedAt()).changedAt(l.getChangedAt())
                        .build())
                .collect(Collectors.toList());
    }

    @Override
    public void checkConfig(Long id) throws BusinessException {
        SysInitFileConfig sysInitFileConfig = this.sysInitFileConfigMapper.selectById(id);
        if (!FileUtil.exist(fileBasePrefix + sysInitFileConfig.getPath())) {
            throw new BusinessException(BusinessExceptionCode.FILE_NOT_EXIST);
        }
        sysInitFileConfig.setChecked(SysInitFileConfig.CHECKED);
        this.sysInitFileConfigMapper.updateById(sysInitFileConfig);
    }
}
